package com.yenlien.traceyun.plant.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.business.interceptor.DataAuth;
import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import com.yenlien.traceyun.business.service.BaseSoilService;
import com.yenlien.traceyun.business.service.rest.RestService;
import com.yenlien.traceyun.plant.entity.Farm;
import com.yenlien.traceyun.plant.entity.FarmType;
import com.yenlien.traceyun.plant.service.FarmService;
import com.yenlien.traceyun.plant.service.PlantService;
import com.yenlien.traceyun.plant.service.ReapService;
import com.yenlien.traceyun.plant.utils.MathUtils;
import com.yenlien.traceyun.webase.controller.BaseController;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 田间管理
 *
 * @author maybe
 * @date 2020年7月27日
 */
@RestController
@RequestMapping("/farm")
public class FarmController extends BaseController {
    @Autowired
    private FarmService farmService;

    @Autowired
    private ReapService reapService;

    @Autowired
    private PlantService plantService;

    @Autowired
    private RestService restService;

    @Autowired
    private BaseSoilService baseSoilService;


    //列表查询
    @DataAuth
    @RequestMapping(value = "/findByList", method = RequestMethod.POST)
    public Object findByList(@RequestBody JSONObject params) {
        Farm farm = new Farm();
        farm.setPage(params.getIntValue("page"));
        return buildPage(farmService.findByList(farm));
    }

    @ApiOperation(value = "获取当前账号的已完成或未完成任务列表", notes = "仅果园二期使用")
    @RequestMapping(value = "/findByListApp", method = RequestMethod.POST)
    public Object findByListApp(@RequestBody Farm farm) {
        return buildPage(farmService.findByListApp(farm));
    }


    @ApiOperation(value = "添加农事操作类型", notes = "仅果园二期使用")
    @RequestMapping(value = "/saveType", method = RequestMethod.POST)
    public Object saveType(@RequestBody FarmType farmType) {
        return success(farmService.saveFarmType(farmType));
    }


    @ApiOperation(value = "获取所有农事操作类型", notes = "仅果园二期使用, 可选参数：state 1=启用， 2=禁用")
    @GetMapping(value = "/getAllType")
    public Object getAllType(String state) {
        return success(farmService.getAllType(state));
    }


    @ApiOperation(value = "批量删除类型", notes = "仅果园二期使用, 参数: 存放id的JSON数组")
    @PostMapping(value = "/delType")
    public Object delType(@RequestBody List<String> idList) {
        farmService.delType(idList);
        return success("success");
    }





    @ApiOperation(value = "查询当前账号下的田间操作类型和负责人姓名", notes = "仅果园二期使用")
    @RequestMapping(value = "/findTypeList", method = RequestMethod.GET)
    public Object findTypeList(String companyId) {
        return success(farmService.findTypeList(StringUtils.isEmpty(companyId) ? UserAuthUtil.getLoginUser().getCompanyId() : companyId));
    }




    //根据ID查询详情
    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable("id") String id) {
        return success(farmService.findById(id));
    }

    //新增
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(Farm farm, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        farmService.save(farm, files);
        return success("success");
    }

    @RequestMapping(value = "/save2", method = RequestMethod.POST)
    public Object save2(@RequestBody Farm farm) throws Exception {
        farmService.save2(farm);
        return success("success");
    }

    //发布任务
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    public Object push(@RequestBody Farm farm) {
        farmService.push(farm);
        return success("success");
    }

    //点击田间管理
    @RequestMapping(value = "/findByUserId", method = RequestMethod.GET)
    public Object findByUserId() {
        String userId = UserAuthUtil.getLoginUser().getId();
        return success(farmService.findByUserId(userId));
    }

    /**
     * 完成任务
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/finish", method = RequestMethod.POST)
    public Object finish(Farm farm, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        farmService.finish(farm, files);
        return success("ok");
    }

    /**
     * 加载任务明细
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/jobdetail/{id}", method = RequestMethod.GET)
    public Object jobDetail(@PathVariable("id") String id) {
        return success(farmService.findById(id));
    }

    /**
     * 地块农事数据回显
     *
     * @return
     */
    @PostMapping("/type")
    public Object type(@RequestBody JSONObject param) {
        return success(farmService.type(param.getString("plantId")));
    }


    /**
     * 种植系统首页
     * 田间操作次数,采购数量统计
     *
     * @return
     */
    @RequestMapping(value = "/fieldCZCount", method = RequestMethod.POST)
    public Object fieldCZCount(@RequestBody JSONObject params) {
        String companyId = params.getString("companyId");
        JSONObject result = new JSONObject();
        if (!StringUtils.isEmpty(companyId)) {
            result.put("fieldCZNum", farmService.fieldCZCount(companyId));        //田间操作次数

            result.put("purchaseNum", MathUtils.df.format(reapService.purchaseCount(companyId)));        //采购数量统计

            String plantAreaCount = plantService.plantAreaCount(companyId);
            plantAreaCount = plantAreaCount == null ? "0" : plantAreaCount;
            result.put("plantAreaNum", MathUtils.df.format(Double.valueOf(plantAreaCount)));        //种植面积统计

            int dkNumSum = baseSoilService.areaNumSum(companyId);        //该公司的地块总数
            int zzdkSum = plantService.plantDKCount(companyId);            //种植地块数(全部采收)
            if (dkNumSum != 0 && zzdkSum != 0) {
                if (dkNumSum <  zzdkSum) {
                    result.put("xgDKSum", 0);        //休耕地块统计
                    return success(result);
                }
                int xgDKSum = dkNumSum - zzdkSum;
                result.put("xgDKSum", xgDKSum);        //休耕地块统计
                return success(result);
            }
            result.put("xgDKSum", dkNumSum);        //休耕地块统计
            //休耕地块数
            return success(result);
        }
        return fail("companyId不能为空");
    }
}
